import { defineStore } from 'pinia'
import { login, logout, getInfo } from '@/api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    username: '',
    avatar: '',
    roles: []
  }),

  actions: {
    async login(loginForm) {
      const { data } = await login(loginForm)
      this.token = data.token
      localStorage.setItem('token', data.token)
    },

    async getInfo() {
      const { data } = await getInfo()
      this.username = data.username
      this.avatar = data.avatar
      this.roles = data.roles
    },

    async logout() {
      await logout()
      this.token = ''
      this.username = ''
      this.avatar = ''
      this.roles = []
      localStorage.removeItem('token')
    },

    resetToken() {
      this.token = ''
      this.username = ''
      this.avatar = ''
      this.roles = []
      localStorage.removeItem('token')
    }
  }
})
